<template>
  <div class="stats-task-chart-wrap">
    <div class="stats-task-chart">
      <div id="service-content-chart" ref="chart"></div>
      <stats-chart-empty v-if="isEmpty">{{$t('common.base.tip.noData')}}</stats-chart-empty> 
    </div>
    <div class="stats-task-table-wrap" v-if="showTable">
      <div class="stats-task-table-header">
        <h3>{{$t('common.label.taskList')}}</h3>

        <button type="button" class="btn btn-primary btn-sm" @click="exportData" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.export') }}</button> 
        <button type="button" class="btn btn-primary btn-sm" @click="exportAllData" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.exportAll') }}</button> 
        <button type="button" class="btn btn-primary btn-sm" @click="showTable = false">{{ $t('common.base.collapse') }}</button>
      </div>
      <div class="stats-task-table">
        <el-table :data="page.list" class="stats-table">

          <el-table-column :label="$t('common.base.serialNumber')" prop="taskNo" width="150px" :show-overflow-tooltip="false">
            <template slot-scope="scope">
              <sample-tooltip :row="scope.row">
                <template slot="content" slot-scope="{isContentTooltip}">
                  <el-tooltip :content="scope.row.taskNo" placement="top" :disabled="!isContentTooltip">
                    <a href="#" @click="openDetail(scope.row)">{{scope.row.taskNo}}</a>
                  </el-tooltip>
                </template>
              </sample-tooltip>
            </template>
          </el-table-column>


          <el-table-column :label="$t('common.base.customer')" prop="customer.name"></el-table-column>
          <el-table-column :label="$t('common.label.taskTemplate')" prop="templateName" width="180px"></el-table-column>
          <el-table-column :label="$t('common.fields.serviceContent.displayName')" prop="serviceContent"></el-table-column>
          
          <el-table-column :label="$t('common.label.principalName')" width="120px">
            <template v-if="scope.row.executor" slot-scope="scope">
              <template v-if="isOpenData">
                <open-data type="userName" :openid="scope.row.executor.staffId"></open-data>
              </template>
              <template v-else>
                {{ scope.row.executor.displayName }}
              </template>
            </template>
          </el-table-column>

          <el-table-column :label="$t('common.base.createUser')" width="120px">
            <template v-if="scope.row.createUser" slot-scope="scope">
              <template v-if="isOpenData">
                <open-data type="userName" :openid="scope.row.createUser.staffId"></open-data>
              </template>
              <template v-else>
                {{ scope.row.createUser.displayName }}
              </template>
            </template>
          </el-table-column>

          <el-table-column :label="$t('common.base.createTime')" width="180px">
            <template slot-scope="scope">
              {{scope.row.createTime | fmt}}
            </template>
          </el-table-column>
        </el-table>

        <el-pagination class="stats-pagination"
          background @current-change="jump"
          :current-page="page.pageNum"
          layout="total, prev, pager, next"
          :total="page.total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>


<script>
import { isOpenData, openAccurateTab } from '@src/util/platform';
import echarts from 'packages/Echarts';
import _ from 'lodash';
import qs from 'src/util/querystring';

import SampleTooltip from 'packages/SampleTooltip';
import { checkButtonDisplayed } from '@src/util/dom';
let chart = null;
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { t } from '@src/locales'
export default {
  name: 'task-serviceContent-chart',
  props: {
    chartData: Object,
    teamId: String,
    timeStart: Number,
    timeEnd: Number,
    exportAuth: Number,
    exportTrack: Function
  },
  data(){
    return {
      isOpenData,
      isEmpty: false,
      showTable: false,
      isButtonDisplayed: checkButtonDisplayed(),
      model: {
        pageNum: 1,
        templateId: ''
      },
      page: {}
    }
  },
  methods: {
    exportAllData(){
      let model = {
        selectType: "serviceContent",
        tagId: this.teamId
      };

      if(this.timeStart) model.timeStart = this.timeStart;
      if(this.timeEnd) model.timeEnd = this.timeEnd;

      window.location.href = '/api/report/outside/stats/typeTask/exportAll?' + qs.stringify(model);

      this.exportTrack(true)
    },
    exportData(){
       let model = {
        pageNum: this.model.pageNum,
        serviceContent: this.model.serviceContent,
        tagId: this.teamId
      };

      if(this.timeStart) model.timeStart = this.timeStart;
      if(this.timeEnd) model.timeEnd = this.timeEnd;

      window.location.href = '/api/report/outside/stats/typeTask/export?' + qs.stringify(model);

      this.exportTrack(false)
    },
    openDetail(row){
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type:PageRoutesTypeEnum.PageTaskView,
        key:row.id,
        titleKey:row.taskNo,
        fromId
      })
      
    },
    jump(currentPage){
      this.model.pageNum = currentPage;
      this.renderTable();
    },
    init(){
      chart = echarts.init(this.$refs.chart);

      chart.on('click', event => {
        let origin = event.data._origin;
        
        this.model.pageNum = 1;
        this.model.serviceContent = origin.name;

        this.renderTable()
      })

      let ctx = this;
      window.addEventListener('resize', _.debounce(function () {
        ctx.render();
      }, 400));
    },
    render(){
      this.showTable = false;
      chart.clear();
      
      let serviceContent = this.chartData.serviceContent || [];

      let arr = [];

      for(let name in serviceContent){
        if(serviceContent[name] && serviceContent[name] > 0) arr.push({
          count: serviceContent[name],
          name: name
        });
      }


      if(arr.length == 0){
        this.isEmpty = true;
        return 
      }

      this.isEmpty = false;

      let sum = 0;
      let legend = [];
      let series = [];
      let data = [];

      arr.forEach(item => {
        sum += item.count;
        legend.push(item.name);

        data.push({
          name: item.name,
          value: item.count,
          _origin: {
            name: item.name,
            value: item.count
          }
        })
      })

      series.push({
        name: t('common.fields.serviceContent.displayName'),
        type: 'pie',
        radius : '55%',
        center: ['50%', '55%'],
        label: {
          normal: {
            formatter: "{b}： {c} ({d}%)"
          }
        },
        data: data,
        itemStyle: {
          normal: {label : {show: true}},
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      })
      
      let taskTypeOption = this.getOptions(legend, series, `${t('report.callConsultChart.total')}：${sum}`)
            
      chart.resize();
      chart.setOption(taskTypeOption);
    },
    getOptions(legend, series, title){
      return {
        color: ["#2ec7c9","#ffb980","#5ab1ef","#d87a80","#5f5f6e","#07a2a4","#9a7fd1","#588dd5","#c05050","#f5994e","#59678c","#7eb00a","#749f83"],
        tooltip : {
          trigger: 'item',
          formatter: `{b} <br/> ${t('common.label.count')}: {c} ({d}%)`
        },
        title: {
          show: true,
          subtext: title,
          right: 100,
          top: 5,
          subtextStyle: {
            color: '#666',
            fontSize: 14
          }
        },
        toolbox: {
          right: 40,
          top: 10,
          feature: {
            saveAsImage: {
              name: t('report.taskProductChart.text2'),
            }
          }
        },
        grid: {
          left: 120,
          containLabel: true
        },
        legend: {
          top: 10,
          bottom: 10,
          left: 5,
          orient: 'vertical',
          data: legend,
          type: 'scroll'
        },
        series: series
      }
    },
    fetchTableData(){
      let model = {
        pageNum: this.model.pageNum,
        serviceContent: this.model.serviceContent,
        tagId: this.teamId,
        pageSize: 10
      };

      if(this.timeStart) model.timeStart = this.timeStart;
      if(this.timeEnd) model.timeEnd = this.timeEnd;

      return this.$http.post('/api/report/outside/stats/task/list', model);
    },
    async renderTable(){
      let instance = this.$loading.show(this.$el);
        
      this.fetchTableData().then(result => {
        this.page = result;
        this.showTable = true;
      })
      .catch(err => console.log(err))
      .finally(() => {
        instance.hide();
      })
    }
  },
  mounted(){
    this.init();
  },
  activated(){
    this.render();
  },
  watch: {
    chartData: {
      deep: true,
      handler: function(value) {
        this.render();
      }
    }
  },
  components: {
    [SampleTooltip.name]: SampleTooltip,
  }
}
</script>